package com.alibaba.job;

import com.alibaba.common.SystemConstants;
import com.alibaba.define.domain.ArticleDO;
import com.alibaba.fastjson.JSON;
import com.alibaba.manager.ArticleManager;
import com.alibaba.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : hanyang
 * @date : 2023-11-08 09:15
 **/

@Component
@Slf4j
public class UpdateViewCountJob {

    private static final String ANSI_GREEN = "\033[32m";

    private static final String ANSI_RESET = "\033[0m";

    @Resource
    RedisCache redisCache;

    @Resource
    ArticleManager articleManager;

    @Scheduled(cron = "0 0/2 * * * ?")
    public void updateViewCount() {
        // 获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.ARTICLE_VIEW_COUNT_KEY);
        List<ArticleDO> articleDOS = new ArrayList<>();
        for (Map.Entry<String, Integer> idAndViewCount : viewCountMap.entrySet()) {
            ArticleDO articleDO = new ArticleDO();
            articleDO.setId(Long.parseLong(idAndViewCount.getKey()));
            articleDO.setViewCount(idAndViewCount.getValue().longValue());
            articleDOS.add(articleDO);
        }
        // db更新操作
        if (articleManager.batchUpdateViewCount(articleDOS)) {
            log.info(ANSI_GREEN + "UpdateViewCountJob ==> updateViewCount update success!" + ANSI_RESET);
        } else {
            log.error("UpdateViewCountJob ==> updateViewCount update error! param:{}", JSON.toJSONString(articleDOS));
        }
    }
}
